package com.cqc.datepicker01;

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements DatePicker.OnDateChangedListener {

    private static final String TAG = "MainActivity";
    private DatePicker datePicker;
    private Button btn1;
    private Button btn2;
    private TimePicker timePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initDatePicker();
        
        initTimePick();

        initDatePickerDialog();

        initTimePickerDialog();
    }

    private void initTimePick() {
        timePicker = (TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(false);//是不是24小时制，默认false（上午+下午）
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
                Toast.makeText(MainActivity.this,"您选择的时间是："+hour+"时"+minute+"分",Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 时间选择器
     */
    private void initTimePickerDialog() {
        btn2 = (Button) findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TimePickerFragment timePickerFragment = new TimePickerFragment();
                timePickerFragment.show(getSupportFragmentManager(),"TimePickerFragment");
            }
        });
    }

    /**
     * 日期选择器
     */
    private void initDatePicker() {
        datePicker = (DatePicker) findViewById(R.id.datePicker);

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        datePicker.init(year,month,dayOfMonth,this);
    }

    /**
     * 日期选择器dialog
     */
    private void initDatePickerDialog() {
        btn1 = (Button) findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment newFragment = new DatePickerFragment();
                newFragment.show(getSupportFragmentManager(), "newFragment");
            }
        });
    }

    @Override
    public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
        Toast.makeText(MainActivity.this, "你选择的日期是："+year+"年"+month+"月"+day+"日", Toast.LENGTH_SHORT).show();
    }
}
